package com.example.demo.services.impl;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.dao.ArticleMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Article;
import com.example.demo.model.Board;
import com.example.demo.model.User;
import com.example.demo.services.IArticleService;
import com.example.demo.services.IBoardService;
import com.example.demo.services.IUserService;
import com.example.demo.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {


   @Autowired
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;


    @Override
    public void create(Article article) {
     //1.非空效验
     if(article==null || article.getUserId()==null || article.getBoardId()==null
        || StringUtil.isEmpty(article.getTitle())
        || StringUtil.isEmpty(article.getContent()))
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }

     // 设置默认值
     article.setVisitCount(0); // 访问数
     article.setReplyCount(0); // 回复数
     article.setLikeCount(0); // 点赞数
     article.setDeleteState((byte) 0);
     article.setState((byte) 0);
     Date date = new Date();
     article.setCreateTime(date);
     article.setUpdateTime(date);
     //写入数据库
     int articleRow=articleMapper.insertSelective(article);
     if(articleRow<=0)
     {
      log.warn(ResultCode.FAILED_CREATE.toString());
      throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
     }

     //获取用户信息
     User user=userService.selectById(article.getUserId());
     if(user==null)
     {
       log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
       throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
     }
      //更新数据
      userService.addOneArticleCountById(user.getId());


      Board board =boardService.selectById(article.getBoardId());
      if(board==null)
      {
        log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, Board id = " + article.getBoardId());
        throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
      }
       //更新数据
     boardService.addOneArticleCountById(board.getId());


     log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId() + ", board id = "
             + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");

     //throw new ApplicationException(AppResult.failed("测试回滚事务"));
    }

    @Override
    public List<Article> selectAll() {

     List<Article> articles=articleMapper.selectAll();
      return articles;
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
     if(boardId==null || boardId<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }
     Board board=boardService.selectById(boardId);
     if(board==null)
     {
      log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
     }

     List<Article> articles=articleMapper.selectByBoardId(boardId);

     return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
     if(id==null || id<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }

     Article article=articleMapper.selectDetailById(id);
     if(article==null)
     {
      log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
     }

     Article updateArticle=new Article();
     updateArticle.setId(article.getId());
     updateArticle.setVisitCount(article.getVisitCount()+1);

     // 保存到数据库
     int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
     if (row != 1) {
      // 打印日志
      log.warn(ResultCode.ERROR_SERVICES.toString());
      // 抛出异常
      throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
     }
     // 更新返回对象的访问次数
     article.setVisitCount(article.getVisitCount() + 1);
     // 返回帖子详情
     return article;
    }

    @Override
    public Article selectById(Long id) {
     if(id==null || id<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }

     Article article=articleMapper.selectByPrimaryKey(id);

       return article;
    }

     @Override
    public void modify(Long id, String title, String content) {
     if(id==null || id<=0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content))
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }
     Article updateArticle=new Article();
     updateArticle.setContent(content);
     updateArticle.setTitle(title);
     updateArticle.setId(id);
     updateArticle.setUpdateTime(new Date());

      // 调用 DAO
      int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
      if (row != 1) {
       // 打印日志
       log.warn(ResultCode.ERROR_SERVICES.toString());
       // 抛出异常
       throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
      }
    }

    @Override
    public void thumbsUpById(Long id) {
     if(id==null || id<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }

     Article article=articleMapper.selectByPrimaryKey(id);

     if(article==null)
     {
      log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
     }
     if(article.getDeleteState()==1 || article.getState()==1)
     {
      log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
     }


     Article updateArticle=new Article();
     updateArticle.setUpdateTime(new Date());
     updateArticle.setLikeCount(article.getLikeCount()+1);
     updateArticle.setId(article.getId());

     // 调用DAO
     int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
     if (row != 1) {
      // 打印日志
      log.warn(ResultCode.ERROR_SERVICES.toString());
      // 抛出异常
      throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
     }
    }

    @Override
    public void deleteById(Long id) {

     if(id==null || id<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }

     Article article=articleMapper.selectByPrimaryKey(id);

     if(article==null)
     {
      log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
     }
     if(article.getDeleteState()==1 || article.getState()==1)
     {
      log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
     }


     Article updateArticle=new Article();
     updateArticle.setDeleteState((byte) 1);
     updateArticle.setId(article.getId());

     // 调用DAO
     int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
     if (row != 1) {
      // 打印日志
      log.warn(ResultCode.ERROR_SERVICES.toString());
      // 抛出异常
      throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
     }
     // 更新版块中的帖子数量
     boardService.subOneArticleCountById(article.getBoardId());
     // 更新用户发帖数
     userService.subOneArticleCountById(article.getUserId());
     log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }

    @Override
    public void addOneReplyCountById(Long id) {

     if(id==null || id<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }
     Article article=articleMapper.selectByPrimaryKey(id);
     if(article==null || article.getDeleteState()==1)
     {
      log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
     }

     if(article.getState()==1)
     {
      log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
     }

     // 构造更新对象
     Article updateArticle = new Article();
     updateArticle.setId(article.getId());
     // 回复数 = 原回复数 + 1
     updateArticle.setReplyCount(article.getReplyCount() + 1);
     updateArticle.setUpdateTime(new Date());
     // 执行更新
     int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
     if (row != 1) {
      // 打印日志
      log.warn(ResultCode.ERROR_SERVICES.toString());
      // 抛出异常
      throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
     }

    }

     @Override
     public List<Article> selectByUserId(Long userId) {

     //参数效验
     if(userId==null || userId<=0)
     {
      log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
     }
//效验用户是否存在
     User user=userService.selectById(userId);
     //不存在
     if(user==null)
     {
      log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"userId="+userId);
      throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
     }

     //获取列表
      List<Article> articles=articleMapper.selectByUserId(userId);

      return articles;
     }


}
